const mongoose = require('mongoose');

const studentSchema = new mongoose.Schema({
  studentId: {
    type: String,
    required: [true, '学号不能为空'],
    unique: true,
    trim: true,
    match: [/^[0-9]{6,10}$/, '学号格式不正确，应为6-10位数字']
  },
  name: {
    type: String,
    required: [true, '姓名不能为空'],
    trim: true,
    minlength: [2, '姓名至少2个字符'],
    maxlength: [20, '姓名最多20个字符']
  },
  class: {
    type: String,
    required: [true, '班级不能为空'],
    trim: true
  },
  scores: [{
    courseName: {
      type: String,
      required: [true, '课程名称不能为空'],
      trim: true
    },
    score: {
      type: Number,
      required: [true, '成绩不能为空'],
      min: [0, '成绩不能小于0'],
      max: [100, '成绩不能大于100']
    }
  }]
}, {
  timestamps: true, // 自动添加createdAt和updatedAt字段
  versionKey: false // 移除__v字段
});

// 创建索引
studentSchema.index({ studentId: 1 });
studentSchema.index({ class: 1 });
studentSchema.index({ score: -1 });
studentSchema.index({ name: 1 });

// 实例方法：获取成绩等级
studentSchema.methods.getGrade = function(score) {
  if (score >= 90) return '优秀';
  if (score >= 80) return '良好';
  if (score >= 70) return '中等';
  if (score >= 60) return '及格';
  return '不及格';
};

// 实例方法：计算平均分
studentSchema.methods.getAverageScore = function() {
  if (!this.scores || this.scores.length === 0) return 0;
  const total = this.scores.reduce((sum, item) => sum + item.score, 0);
  return (total / this.scores.length).toFixed(2);
};

// 静态方法：按班级统计
studentSchema.statics.getClassStatistics = async function(className, courseName) {
  const matchStage = {};
  if (className) matchStage.class = className;
  
  return await this.aggregate([
    { $match: matchStage },
    { $unwind: '$scores' },
    { $match: courseName ? { 'scores.courseName': courseName } : {} },
    {
      $group: {
        _id: '$class',
        count: { $sum: 1 },
        avgScore: { $avg: '$scores.score' },
        maxScore: { $max: '$scores.score' },
        minScore: { $min: '$scores.score' }
      }
    }
  ]);
};

const Student = mongoose.model('Student', studentSchema);

module.exports = Student;
